package com.jhc.utils;

import cn.hutool.core.util.ObjectUtil;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author zhuzhixu
 */
public class VerifyPageDtoUtil {
    /**
     * 反射获取对象实体参数转化成map
     *
     * @param convertObj 转化对象
     * @param <T>        传入泛型
     * @return
     */
    public static <T> Map<String, Object> convertParamMap(T convertObj) {
        if (ObjectUtil.isNotNull(convertObj)) {
            Map<String, Object> saveParamObj = new HashMap<>(5);
            Class convertObjClass = convertObj.getClass();
            Field[] fields = convertObjClass.getDeclaredFields();
            Arrays.stream(fields).forEach(filed -> {
                filed.setAccessible(true);
                String filedName = filed.getName();
                Object filedValue = null;
                try {
                    filedValue = filed.get(convertObj);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (ObjectUtil.isNotNull(filedValue)) {
                    saveParamObj.put(filedName, filedValue);
                }
            });
            return saveParamObj;
        }
        return null;
    }

    /**
     * 验证map中参数是否符合该实体对象
     *
     * @param map       数据map
     * @param verifyObj 验证对象
     * @param <T>       传入泛型
     * @return
     */
    public static <T> Boolean verifyItem(Map<String, Object> map, T verifyObj) throws NoSuchFieldException, IllegalAccessException {
        if (ObjectUtil.isNotNull(map)) {
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
            Boolean flag = true;
            while (iterator.hasNext()) {
                Map.Entry<String, Object> next = iterator.next();
                String key = next.getKey();
                Object value = next.getValue();
                Field f = verifyObj.getClass().getDeclaredField(key);
                f.setAccessible(true);
                Object itemValue = f.get(verifyObj);
                if (!value.equals(itemValue)) {
                    flag = false;
                    break;
                }
            }
            return flag;
        }
        return true;
    }
}
